import React, { useState } from "react";
import style from "./style.module.scss";
import { Swiper, Notify, Popup } from "react-vant";
import { useBoolean, useMount, useSetState, useUpdateEffect } from "ahooks";
import {
  VideoVoListParams,
  addCollectVedio,
  buyVedio,
  cancelCollectVedio,
  getCommentVedioList,
  getVideoCategoryList,
  getVideoVoList,
} from "../../api/vedio";
// import VideoJS from "video.js";
import playUrl from "../../assets/images/icon/common resource/hdpi/common_icon_time_out_n.png";

import payUrl from "../../assets/images/icon/common resource/hdpi/common_icon_toll_n.png";
import notCollectUrl from "../../assets/images/icon/common resource/hdpi/common_button_collection_large_n.png";
import collectUrl from "../../assets/images/icon/common resource/hdpi/common_button_collection_large_s.png";
import commentUrl from "../../assets/images/icon/common resource/hdpi/common_icon_comment_large_n.png";
import writeUrl from "../../assets/images/icon/common resource/hdpi/common_icon_close_live_commenting_n.png";
import { useNavigate } from "react-router-dom";
import { Barra, VedioInfo } from "../../components";
interface VedioTtilte {
  id: number;
  name: string;
}

export interface VedioList {
  // 摘要
  abstracts: string;
  // 已买数量
  buyNum: number;
  // 健康视频类目id
  categoryId: number;
  // 时长
  duration: number;
  // 健康视频id
  id: number;
  // 原始视频url
  originalUrl: string;
  // 单价
  price: number;
  // 剪切视频url(试看)
  shearUrl: string;
  // 标题
  title: string;
  // 购买  1已经收藏  2没收藏
  whetherBuy: number;
  // 收藏  1已经收藏  2没收藏
  whetherCollection: number;
}

const vedioEls: HTMLVideoElement[] = [];

const Index: React.FC = () => {
  const navigate = useNavigate();
  // 标题列表
  const [vedioListTitle, setVedioListTitle] = useState<VedioTtilte[]>([]);
  // 视频列表
  const [vedioList, setVedioList] = useState<VedioList[]>([]);
  // 当前播放位置
  const [currentIndex, setCurrentIndex] = useState(0);
  // 当前弹幕
  const [barrageList, setBarrageList] = useState<string[]>([]);
  // 当前播放状态
  const [autoPlay, { setFalse, setTrue }] = useBoolean(false);
  // 请求参数
  const [params, setParams] = useSetState<VideoVoListParams>({
    categoryId: -1,
    count: 100,
    page: 1,
  });
  // 当前进度列表
  const [width, setWidth] = useState<string>("0%");
  // 获取视频列表
  const getVedioList = async () => {
    const resp = await getVideoVoList(params);
    setVedioList(resp.result);
  };
  // 获取当前位置弹幕视频弹幕
  const getVedioComment = async (i: number) => {
    const videoId = vedioList[i].id;
    const resp = await getCommentVedioList(videoId);
    const result = resp.result.map((v) => v.content).slice(0, 100);
    setBarrageList(result);
  };
  // 上下滑动事件
  const onChange = (nextIndex) => {
    vedioEls[currentIndex] && vedioEls[currentIndex].pause();
    setCurrentIndex(() => {
      autoPlay && vedioEls[nextIndex] && vedioEls[nextIndex].play();
      getVedioComment(nextIndex);
      return nextIndex;
    });
  };
  // 第一次开始播放
  const play = (i: number) => {
    setTrue();
    vedioEls[i].play();
    getVedioComment(i);
  };
  // 暂停
  const pause = (i: number) => {
    setFalse();
    vedioEls[i].pause();
  };
  // 收藏
  const oprationCollect = async (v: VedioList) => {
    if (v.whetherCollection === 2) {
      const { status, message } = await addCollectVedio(v.id);
      if (status === "0000") {
        Notify.show({ type: "success", message });
        getVedioList();
      } else if (status === "9999") {
        Notify.show({ type: "danger", message });
        navigate('/login?from=/vedio')
      }
    } else {
      const { status, message } = await cancelCollectVedio(v.id);
      if (status === "0000") {
        Notify.show({ type: "success", message });
        getVedioList();
      } else if (status === "9999") {
        Notify.show({ type: "danger", message });
      }
    }
  };
  // 购买视频
  const buy = async (v: VedioList) => {
    const { status, message } = await buyVedio(v.id, v.price);
    if (status === "0000") {
      Notify.show({ type: "success", message });
    } else if (status === "9999") {
      Notify.show({ type: "danger", message });
    }
  };
  // 购买视频底部弹框状态
  const [visible, setVisible] = useState(false);
  // 管看结束事件
  const onEnded = () => {
    console.log("结束");
  };
  // 挂载事件
  useMount(async () => {
    const resp = await getVideoCategoryList();
    setVedioListTitle(resp.result);
    setParams({
      categoryId: resp.result[0].id,
    });
  });
  // id 更新
  useUpdateEffect(() => {
    if (params.categoryId) {
      getVedioList();
    }
  }, [params.categoryId]);

  return (
    <div className={style["vedio"]}>
      {vedioList.length > 0 && (
        <Swiper
          className={style["swiper"]}
          loop={false}
          vertical
          stuckAtBoundary
          rubberband={false}
          onChange={(i) => onChange(i)}
          indicator={false}
        >
          {vedioList.map((v, i) => {
            return (
              <Swiper.Item className={style["swiper-item"]} key={v.id}>
                <div className={style["item"]}>
                  {/* 视频 */}
                  <video
                    className={style["vedio"]}
                    ref={(ref) => (vedioEls[i] = ref as HTMLVideoElement)}
                    preload="auto"
                    onClick={() => pause(i)}
                    controls={false}
                    onEnded={() => onEnded()}
                    onTimeUpdate={(e) => {
                      const tar = e.target as HTMLVideoElement;
                      setWidth((tar.currentTime / tar.duration) * 100 + "%");
                    }}
                  >
                    <source
                      src={v.whetherBuy === 1 ? v.originalUrl : v.shearUrl}
                    />
                  </video>
                  {/* 弹幕 */}
                  {barrageList.length > 0 && i === currentIndex && (
                    <div className={style["barra"]}>
                      <Barra barrageList={barrageList} autoPlay={autoPlay}></Barra>
                    </div>
                  )}
                  {/* 播放按钮 */}
                  <img
                    src={playUrl}
                    alt=""
                    className={style["play"]}
                    onClick={() => play(i)}
                    style={{ display: autoPlay ? "none" : "block" }}
                  />
                  {/* 右侧icon */}
                  <div className={style["right"]}>
                    {v.whetherBuy === 1 ? (
                      <img src={commentUrl} alt="" />
                    ) : (
                      <img src={payUrl} alt="" onClick={() => buy(v)} />
                    )}
                    <img
                      src={
                        v.whetherCollection === 2 ? notCollectUrl : collectUrl
                      }
                      alt=""
                      onClick={() => oprationCollect(v)}
                    />
                    <img src={writeUrl} alt="" />
                  </div>
                  {/* 上箭头 */}
                  <VedioInfo
                    v={v}
                    width={i === currentIndex ? width : "0%"}
                    touchMove={(progerss) => {
                      const el = vedioEls[currentIndex];
                      el.currentTime = progerss * el.duration;
                    }}
                  ></VedioInfo>
                </div>
              </Swiper.Item>
            );
          })}
        </Swiper>
      )}

      <Popup
        visible={visible}
        onClose={() => setVisible(false)}
        position="bottom"
      >
        <div>内容</div>
      </Popup>
    </div>
  );
};

export default Index;
